<template>
  <div ref="barRef" :style="{ height, width }" />
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onBeforeMount, onBeforeUnmount, onMounted, ref, watch } from 'vue';

const props = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '400px',
  },
  chartData: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const barRef = ref<any>(null);
const barData = ref<any>(null);

onMounted(() => {
  barData.value = props.chartData;
  initChart();
});

watch(() => props.chartData, (newValue, oldValue) => {
  barData.value = newValue;
  initChart();
})

const initChart = () => {
  const myChart = echarts.init(barRef.value);
  myChart.setOption(optionConfig());
};

// 配置参数
const optionConfig = () => {
  const option = {
    legend: {
      show: true,
    },
    tooltip: {},
    dataset: {
      source: barData.value,
    },
    xAxis: { type: 'category' },
    yAxis: {},
    series: [
      { type: 'bar', barWidth: 26 },
      { type: 'bar', barWidth: 26 },
      { type: 'bar', barWidth: 26 },
    ],
  };
  return option;
};
</script>

<style lang="scss" scoped></style>
